package com.mavenweb.demo.utils;

import lombok.Getter;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;

public class MybatisUtils {

    @Getter
    private static SqlSessionFactory sqlSessionFactory;
    private static final ThreadLocal<SqlSession> threadLocal = new ThreadLocal<>();
    private static final String RESOURCE = "mybatis-config.xml";
    static {
        try {
            SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder();
            sqlSessionFactory = factoryBuilder.build(Resources.getResourceAsReader(RESOURCE));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static SqlSession getSqlSession(Boolean isAutoCommit) {
        SqlSession sqlSession = threadLocal.get();
        if (sqlSession == null) {
            sqlSession = sqlSessionFactory.openSession(isAutoCommit);
            threadLocal.set(sqlSession);
        }
        return sqlSession;
    }
    public static SqlSession getSqlSession() {
        return getSqlSession(true);
    }

    public static <T> T getMapper(Class<T> clazz){
        return getSqlSession(true).getMapper(clazz);
    }

}
